<?php

declare(strict_types=1);

namespace app\admin\model\auth;

use sheep\model\auth\Admin as BaseAdmin;
use app\seller\model\Store as StoreModel;
use app\operations\model\Organ as OrganModel;

class Admin extends BaseAdmin
{
    protected $name = 'admin';

    protected $type = [
        'role_id'     => 'integer',
        'login_time'  =>  'timestamp',
    ];

    protected $json = [];    // 自动 json 转换

    // 追加属性
    protected $append = [
        'legal_id_type_text',
        'entity_type_text',
    ];


    public function legalIdtypeList()
    {
        return [
            'id_card' => '居民身份证',
        ];
    }

    public function entityTypeList()
    {
        return [
            'company' => '企业',
            'individual' => '个人',
        ];
    }


    /**
     * 通用类型获取器
     *
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getLegalIdtypeTextAttr($value, $data)
    {
        $value = $value ?: ($data['legal_id_type'] ?? null);

        $list = $this->legalIdtypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getEntityTypeTextAttr($value, $data)
    {
        $value = $value ?: ($data['entity_type'] ?? null);

        $list = $this->entityTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }





    // 模型事件写入前
    public static function onBeforeWrite($admin)
    {
        $input_password = request()->param('password');
        if ($input_password && in_array(request()->action(), ['add', 'edit'])) {      // 包含管理员添加编辑，和编辑自己资料
            // 每次修改密码，都重新生成 salt
            $salt = mt_rand(1000, 9999);
            $admin->salt = $salt;
            $admin->password = (new static)->encryptPassword($input_password, $salt);
        }
    }

    public function role()
    {
        return $this->hasOne("Role", "id", "role_id")->field("id, name");
    }

    public function store()
    {
        return $this->hasMany(StoreModel::class, "organ_id", "organ_id");
    }


    public function organ()
    {
        return $this->belongsTo(OrganModel::class, 'organ_id', 'id');
    }


}
